﻿using Developer.Core.FrameWork.Common.Users.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Developer.Core.FrameWork.Common.Users.Binder
{
    /// <summary>
    /// 系统用户模型绑定
    /// </summary>
    public class SysUserModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
                throw new ArgumentNullException(nameof(bindingContext));

            if (bindingContext.ModelType == typeof(SysUser))
            {
                SysUser sysUser = new SysUser();

                HttpContext httpContext = bindingContext.HttpContext;

                ClaimsPrincipal claimsPrincipal = httpContext.User;

                IEnumerable<Claim> claims = claimsPrincipal.Claims;

                if (claims.ToList().Count == 0)
                    throw new Exception("授权失败，没有登录");

                foreach (var claim in claims)
                {
                    if ("sub".Equals(claim.Type))
                        sysUser.UserId = Convert.ToString(claim.Value);

                    if ("amr".Equals(claim.Type))
                        sysUser.UserName = claim.Value;
                }

                bindingContext.Result = ModelBindingResult.Success(sysUser);
            }

            return Task.CompletedTask;
        }
    }
}
